<template>
    <view>
        <button class="niceButton4" @click="selectGoodsShow=true">选择货物</button>
        <view class="selected-items">
            <p>选择的货物:</p>
            <!-- 显示选择的货物信息 -->
            <view class="selected-items">
                <view v-for="(item, itemIndex) in selectedProds" :key="item.productId" class="item">
                    {{ item.prodName}}
                    <picker @change="bindPickerChange($event, itemIndex)" :value="item.selectedRuleIndex || 0"
                        :range="formatRules(item.priceRules)">
                        <view class="uni-input">
                            选择卸货规则：
                            {{ item.priceRules[(item.selectedRuleIndex || 0)].key }}
                            (价格：{{ item.priceRules[(item.selectedRuleIndex || 0)].value }})
                        </view>
                    </picker>
                    数量：<u-number-box v-model="item.prodCount" integer></u-number-box>
                </view>


            </view>
        </view>
        <view class="yt-list">
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">商品合计</text>
                <text class="cell-tip">￥{{order.totalAmount}}</text>
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">区号:</text>
                <input class="desc" type="text" v-model="order.areaNum" placeholder="请填写卸货区号信息"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">门牌号:</text>
                <input class="desc" type="text" v-model="order.stallNum" placeholder="请填写门牌号"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">详细地址:</text>
                <input class="desc" type="text" v-model="order.address" placeholder="请填写详细地址"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">司机姓名:</text>
                <input class="desc" type="text" v-model="order.senderName" placeholder="请填写配送员姓名"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">驾驶员电话:</text>
                <input class="desc" type="text" v-model="order.senderPhone" placeholder="请填写送货驾驶员电话"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell b-b">
                <text class="cell-tit clamp">配送车牌号:</text>
                <input class="desc" type="text" v-model="order.senderCar" placeholder="请填写送货车牌号"
                    placeholder-class="placeholder" />
            </view>
            <view class="yt-list-cell desc-cell">
                <text class="cell-tit clamp">备注:</text>
                <input class="desc" type="text" v-model="order.note" placeholder="请填写备注信息"
                    placeholder-class="placeholder" />
            </view>
        </view>
        <u-button class="u-reset-button" style="
			                                   width: 30%;
			                                   height: 37px;
			                                   line-height: 37px;
			                                   margin-bottom: 4vh;
			                                   transform: translateY(15px);" @click="submitOrder">发布订单</u-button>

        <u-popup :show="selectGoodsShow" mode="bottom" @close="close" @open="open">
            <view class="selectGoods-info">
                <view class="info-item">
                    <view class="info-item-tip">
                        选择货品：
                    </view>
                    <view class="info-item-content">
                        <view class="product-selection">
                            <view v-for="(product, index) in productList" :key="index"
                                :class="['product-button', { active: selectedIds.includes(product.productId) }]"
                                @click="selectproduct(product, index)">
                                {{ product.prodName }}
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <button class="u-reset-button" style="
			                                   width: 30%;
			                                   height: 37px;
			                                   line-height: 37px;
			                                   margin-bottom: 4vh;
			                                   transform: translateY(15px);
			" @click="submitSelect" type="default">确认</button>
            <button class="u-reset-button" style="
			                                    width: 30%;
			                                    height: 37px;
			                                    line-height: 37px;
			                                    margin-bottom: 10vh;
			                                    transform: translateY(15px);
			" @click="close" type="default">关闭</button>
        </u-popup>

        <tabBar></tabBar>
    </view>

</template>

<script>
    import {
        productApi
    } from '../../api';


    export default {
        data() {
            return {
                selectGoodsShow: false,
                selectedProds: [],
                prods: [],
                selectedIds: [],
                show: false,
                index: 0,
				userInfo: {},
                order: {
                    userId: '',
                    shopId: '',
                    userName: '',
                    totalAmount: 0,
                    address: '',
                    areaNum: '',
                    stallNum: '',
                    senderName: '',
                    senderPhone: '',
                    senderCar: '',
                    note: '',
                    prods: [],
                },
                productList: [
                	{
                		keywords: "1",
                		priceRules: "string",
                		prodCategoryId: 0,
                		prodCategoryName: "string",
                		prodName: "大蒜",
                		prodNote: "string",
                		prodPrice: 0,
                		prodUnit: "string",
                		prodUnitWeight: 0,
                		productId: 1,
                		sort: 0
                	},
                	{
                		keywords: "2",
                		priceRules: "string",
                		prodCategoryId: 0,
                		prodCategoryName: "string",
                		prodName: "生姜",
                		prodNote: "string",
                		prodPrice: 0,
                		prodUnit: "string",
                		prodUnitWeight: 0,
                		productId: 2,
                		sort: 0
                	},
                	
                ],

            }
        },
        watch: {
            selectedProds: {
                handler(newValue) {
                    // 每当 selectedProds 发生变化时调用这个函数
                    this.collectData();
                },
                deep: true // 深度监听数组中的对象
            }
        },
        methods: {
			//从Storage取数据
			getInfo(){
				//获取用户信息
				const user = uni.getStorageSync('user');
				if (user){
					this.userInfo = JSON.parse(user).value;
					console.log(JSON.parse(user).value);
					console.log('user',this.userInfo);
				} else {
					console.log('未找到用户信息');
				}
			},
            formatRules(rules) {
                return rules.map(rule => `${rule.key}(${rule.value}元)`)
            },
            parsePriceRules(priceRulesString, prodPrice) {
                if (!priceRulesString) {
                    return [{
                        key: '默认',
                        value: prodPrice
                    }]
                }
                try {
                    return JSON.parse(priceRulesString);
                } catch (e) {
                    console.error('解析 priceRules 字符串时出错', e);
                    return [];
                }
            },
            extractKeyValueFromString(str) {
                try {
                    // 将字符串解析为对象
                    const obj = JSON.parse(str);

                    // 从对象中提取 key 和 value
                    const {
                        key,
                        value
                    } = obj;

                    return {
                        key,
                        value
                    };
                } catch (error) {
                    console.error("Invalid JSON string:", error);
                    return null; // 如果解析失败，返回 null
                }
            },
            selectproduct(prod, index) {
                if (this.selectedIds.includes(prod.productId)) {
                    this.selectedIds = this.selectedIds.filter(id => id !== prod.productId);
                } else {
                    this.selectedIds.push(prod.productId);
                }
            },
            selectGoods(selectItem) {
                this.currOrder = selectItem;
                console.log(`this.currOrder.orderId:${this.currOrder.orderId}`)
                this.allocationShow = true;

            },
            open() {
                // console.log('open');
            },
            close() {
                this.selectGoodsShow = false
                // console.log('close');
            },
            submitSelect() {
                this.selectedProds = this.productList.filter(item => this.selectedIds.includes(item.productId));
                this.selectGoodsShow = false;
            },
            bindPickerChange: function(event, itemIndex) {
                console.log(itemIndex)
                const selectedRuleIndex = event.detail.value;
                console.log('picker发送选择改变，携带值为', selectedRuleIndex);
                if (typeof itemIndex !== 'undefined') {
                    this.$set(this.selectedProds[itemIndex], 'selectedRuleIndex', selectedRuleIndex);
                }
            },
            collectData() {
                // 创建一个新数组，用于保存处理后的数据
                this.order.prods = this.selectedProds.map(item => ({
                    productId: item.productId,
                    prodName: item.prodName,
                    prodPrice: 40,
                    prodCount: item.prodCount,
                    carNums: 0,
                    prodUnit: "string",
                    priceRule: "string",
                    mayAmount: item.prodCount * item.priceRules[item.selectedRuleIndex].value,
                }));

                console.log(`this.selectedProds:`);
                console.log(this.selectedProds);
                console.log(`item:${item}`);
                console.log(`this.order.prods:${this.order.prods}`);
                // console.log(this.collectedData);
                // 你可以根据需求进一步处理这个数组，例如发送到服务器
            },
            computeMayAmount() {

            },
            submitOrder() {
				this.order.userId= this.userInfo.userId;
				this.order.shopId= this.userInfo.shopId;
                console.log('userInfo'+this.userInfo.value);
                console.log("order"+this.order);
            },
            async fetchShopProductList(id) {
				console.log(id);
                try {
                    uni.showLoading({
                        title: "请稍后"
                    })
                    const {
                        code,
                        data
                    } = await productApi.fetchShopProductList(id);
                    if (code == 200) {
                        this.productList = data.map(item => ({
                            ...item,
                            priceRules: this.parsePriceRules(item.priceRules, item.prodPrice),
                            selectedRuleIndex: 0, //默认选择第一个规则
                            prodCount: 1 //初始1个
                        }));
                        // console.log("data:"+this.productList[0].priceRules);
                        // console.log(JSON.stringify(this.productList[0].priceRules, null, 2))
                        // console.log(JSON.stringify(this.productList, null, 2));
                    }
                } finally {
                    uni.hideLoading();
                }

            }
        },
        mounted() {
			this.getInfo();
            this.fetchShopProductList(this.userInfo.shopId);
			
        },
    }
</script>

<style lang="scss">
    .product-selection {
        display: flex;
        flex-flow: wrap;
        margin-bottom: 16upx;
    }

    .product-button {
        padding: 8upx 16upx;
        margin: 5px;
        border: 1upx solid #d9a1a1;
        border-radius: 4upx;
        cursor: pointer;
        background-color: #ffe6e6;
    }

    .product-button.active {
        background-color: #e66973;
        color: white;
    }

    .niceButton4 {
        background-color: #ff428a;
        border: none;
        border-radius: 12px;
        color: white;
        /* padding: 15px 32px; */
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
        transition-duration: 0.4s;
        -webkit-transition-duration: 0.4s;
    }

    .niceButton4:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, .24),
            0 17px 50px 0 rgba(0, 0, 0, .19);
    }


    .selectGoods-info {
        min-height: 65vh;
        max-height: 80vh;
        overflow: scroll;
        margin-top: 30px;
        padding: 20px;

        .title {
            font-size: 20px;
            margin-bottom: 15px;
        }

        .info-item {
            margin-top: 35px;
            display: flex;

            .info-item-tip {
                font-size: 14px;
                width: 100px;
                padding-left: 30rpx;
            }

            .info-item-content {
                font-size: 14px;
                font-weight: 700;
                width: 74%;
            }
        }
    }

    .u-checkbox {
        margin-top: 2px;
        margin-bottom: 10px !important;
    }

    .yt-list {
        margin-top: 16upx;
        background: #fff;
        // padding-top: 40px;
    }

    .yt-list-cell {
        display: flex;
        align-items: center;
        padding: 10upx 30upx 10upx 40upx;
        line-height: 70upx;
        position: relative;

        &.cell-hover {
            background: #fafafa;
        }

        &.b-b {
            .cell-tit {
                max-width: 200upx;
            }
        }

        &.b-b:after {
            left: 30upx;
        }

        .cell-icon {
            height: 32upx;
            width: 32upx;
            font-size: 22upx;
            color: #fff;
            text-align: center;
            line-height: 32upx;
            background: #f85e52;
            border-radius: 4upx;
            margin-right: 12upx;

            &.hb {
                background: #ffaa0e;
            }

            &.lpk {
                background: #3ab54a;
            }

        }

        .cell-more {
            align-self: center;
            font-size: 24upx;
            color: $font-color-light;
            margin-left: 8upx;
            margin-right: -10upx;
        }

        .cell-tit {
            flex: 1;
            /* 	font-size: 26upx; */
            color: $font-color-light;
            margin-right: 10upx;
        }

        .cell-tip {
            font-size: 26upx;
            color: $font-color-dark;
        }

        &.desc-cell {
            .cell-tit {
                max-width: 90upx;
            }
        }

        .desc {
            flex: 1;
            font-size: $font-base;
            color: $font-color-dark;
        }

        .integration {
            flex: 1;
            font-size: $font-base;
            color: $font-color-dark;
            text-align: right;
        }
    }
	.form-section {
	
	    .u-form-item__body__left {
	        width: 175rpx !important;
	        padding-left: 5px;
	        background: #ffe7e79c;
	        border: solid 1px #FBDBE1;
	        border-right: 0;
	
	        text {
	            text-align-last: justify !important;
	            display: inline !important;
	        }
	    }
	
	    .u-form-item__body__right {
	        padding-left: 5px;
	        background: #ffffff;
	        border: solid 1px #FBDBE1;
	        border-left: 0;
	        min-height: 40px;
	
	        text {
	            // text-align-last: justify !important;
	            display: inline !important;
	        }
	
	        .u-picker__view__column {
	            text {
	                // text-align-last: center !important;
	                display: block !important;
	            }
	        }
	    }
	
	}
</style>